import React, {Component} from 'react';
import 'whatwg-fetch';
import {Button, List, Toast} from 'antd-mobile';
import moment from 'moment';
import './style.scss';

const Item = List.Item;
moment.locale('zh-cn', {
  months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
  monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
  weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
  weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
  weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
  longDateFormat: {
    LT: 'Ah点mm分',
    LTS: 'Ah点m分s秒',
    L: 'YYYY-MM-DD',
    LL: 'YYYY年MMMD日',
    LLL: 'YYYY年MMMD日Ah点mm分',
    LLLL: 'YYYY年MMMD日ddddAh点mm分',
    l: 'YYYY-MM-DD',
    ll: 'YYYY年MMMD日',
    lll: 'YYYY年MMMD日Ah点mm分',
    llll: 'YYYY年MMMD日ddddAh点mm分'
  },
  meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
  meridiemHour: function (hour, meridiem) {
    if (hour === 12) {
      hour = 0;
    }
    if (meridiem === '凌晨' || meridiem === '早上' ||
      meridiem === '上午') {
      return hour;
    } else if (meridiem === '下午' || meridiem === '晚上') {
      return hour + 12;
    } else {
      // '中午'
      return hour >= 11 ? hour : hour + 12;
    }
  },
  meridiem: function (hour, minute, isLower) {
    var hm = hour * 100 + minute;
    if (hm < 600) {
      return '凌晨';
    } else if (hm < 900) {
      return '早上';
    } else if (hm < 1130) {
      return '上午';
    } else if (hm < 1230) {
      return '中午';
    } else if (hm < 1800) {
      return '下午';
    } else {
      return '晚上';
    }
  },
  calendar: {
    sameDay: function () {
      return this.minutes() === 0 ? '[今天]Ah[点整]' : '[今天]LT';
    },
    nextDay: function () {
      return this.minutes() === 0 ? '[明天]Ah[点整]' : '[明天]LT';
    },
    lastDay: function () {
      return this.minutes() === 0 ? '[昨天]Ah[点整]' : '[昨天]LT';
    },
    nextWeek: function () {
      var startOfWeek, prefix;
      startOfWeek = moment().startOf('week');
      prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]';
      return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
    },
    lastWeek: function () {
      var startOfWeek, prefix;
      startOfWeek = moment().startOf('week');
      prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]';
      return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
    },
    sameElse: 'LL'
  },
  ordinalParse: /\d{1,2}(日|月|周)/,
  ordinal: function (number, period) {
    switch (period) {
      case 'd':
      case 'D':
      case 'DDD':
        return number + '日';
      case 'M':
        return number + '月';
      case 'w':
      case 'W':
        return number + '周';
      default:
        return number;
    }
  },
  relativeTime: {
    future: '%s内',
    past: '%s前',
    s: '几秒',
    m: '1 分钟',
    mm: '%d 分钟',
    h: '1 小时',
    hh: '%d 小时',
    d: '1 天',
    dd: '%d 天',
    M: '1 个月',
    MM: '%d 个月',
    y: '1 年',
    yy: '%d 年'
  },
  week: {
    // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
    dow: 1, // Monday is the first day of the week.
    doy: 4  // The week that contains Jan 4th is the first week of the year.
  }
});


export default class autoDaka extends Component {
  constructor(props) {
    super(props);
    const that = this;
    that.state = {
      'name': '', // 用户姓名
      'access_token': '', // access_token
      'token': '', // token
      'signInState': false, // 签到状态
      'signInText': '签到', // 签到文字
      'signOutState': false, // 签退状态
      'signOutText': '签退', // 签退文字
      'updateSignOutState': 'none', // 更新签退状态
    }
    that.cardInfo = that.cardInfo.bind(that);
    that.dakaClick = that.dakaClick.bind(that);
  }

  componentDidMount() {
    const that = this;
    const id = '169582'; // 获取工号
    // 获取access_token
    fetch('/daka/iSSC/wxapi/v2/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include'
    }).then((response) => {
      return response.json();
    }).then((data) => {
      if (data.access_token) {
        const access_token = data.access_token;
        that.setState({
          access_token
        });
        // 通过员工工号获取token
        fetch('/daka/iSSC/wxapi/v2/user', {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' + access_token,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            number: id,
            UserName: ''
          }),
          credentials: 'include'
        }).then((response) => {
          return response.json();
        }).then((res) => {
          if (res.ResultCode != 1000) {
            Toast.fail('获取用户信息失败，请输入正确的工号', 3);
          } else {
            const token = res.token;
            const name = res.name;
            that.setState({
              token,
              name
            });
            that.cardInfo(access_token, token);
          }
        }).catch((err) => {
          console.log('err', err);
        })
      } else {
        Toast.fail('获取access_token失败', 3);
      }
    }).catch((err) => {
      console.log('err', err);
    })


    const workday = [ // 补班
      '2019/02/02',
      '2019/02/03',
      '2019/09/29',
      '2019/10/12'
    ];
    const screen = [    // 节假日
      '2019/02/04', // 春节
      '2019/02/05', // 春节
      '2019/02/06', // 春节
      '2019/02/07', // 春节
      '2019/02/08', // 春节
      '2019/02/09', // 春节
      '2019/02/10', // 春节

      '2019/04/05', // 清明节
      '2019/04/06', // 清明节
      '2019/04/07', // 清明节

      '2019/05/01', // 劳动节

      '2019/06/07', // 端午节
      '2019/06/08', // 端午节
      '2019/06/09', // 端午节

      '2019/09/13', // 中秋节
      '2019/09/14', // 中秋节
      '2019/09/15', // 中秋节

      '2019/10/01', // 国庆节
      '2019/10/02', // 国庆节
      '2019/10/03', // 国庆节
      '2019/10/04', // 国庆节
      '2019/10/05', // 国庆节
      '2019/10/06', // 国庆节
      '2019/10/07', // 国庆节


    ]

    // 每天六点获取一次打卡状态  每过一小时判断一次
    setInterval(() => {
      const hour = moment().format('HH'); // 当前几时
      if (hour == '06') {
        // 获取access_token
        fetch('/daka/iSSC/wxapi/v2/token', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          credentials: 'include'
        }).then((response) => {
          return response.json();
        }).then((data) => {
          if (data.access_token) {
            const access_token = data.access_token;
            that.setState({
              access_token
            });
            // 通过员工工号获取token
            fetch('/daka/iSSC/wxapi/v2/user', {
              method: 'POST',
              headers: {
                'Authorization': 'Bearer ' + access_token,
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                number: id,
                UserName: ''
              }),
              credentials: 'include'
            }).then((response) => {
              return response.json();
            }).then((res) => {
              if (res.ResultCode != 1000) {
                Toast.fail('获取用户信息失败，请输入正确的工号', 3);
              } else {
                const token = res.token;
                const name = res.name;
                that.setState({
                  token,
                  name
                });
                that.cardInfo(access_token, token);
              }
            }).catch((err) => {
              console.log('err', err);
            })
          } else {
            Toast.fail('获取access_token失败', 3);
          }
        }).catch((err) => {
          console.log('err', err);
        })
      }
    }, 3600000);

    // 每隔十四分钟执行一次
    setInterval(() => {
      const signInState = that.state.signInState; // 上班打卡状态
      const signOutState = that.state.signOutState; // 下班打卡状态
      // 获取当前时间，判断是否应该打卡
      const date = moment().format('YYYY/MM/D'); // 当前日期
      const weekend = moment().format('d'); // 6:周六 0:周日
      const hour = moment().format('HH'); // 当前几时
      // 循环节假日
      screen.forEach((data) => {
        // 如果当前不是节假日并且不是周六周日并且是在八点多并且今天没打过卡
        if (date != data && weekend != '6' && weekend != '0' && hour == '08' && !signInState) {
          that.dakaClick('签到');
        } else if (date != data && weekend != '6' && weekend != '0' && hour == '20' && !signOutState) {
          that.dakaClick('签退');
        }
      });
      // 循环补班日
      workday.forEach((val) => {
        // 如果当前日期是补班日并且是在八点多并且今天没打过卡
        if (date == val && hour == '08' && !signInState) {
          that.dakaClick('签到');
        } else if (date == val && hour == '20' && !signOutState) {
          that.dakaClick('签退');
        }
      });
    }, 840000);
  }

  // 获取打卡状态信息
  cardInfo(access_token, token) {
    const that = this;
    // 通过token获取打卡信息
    fetch('/daka/iSSC/wxapi/v2/current', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer ' + access_token,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({token: token}),
      credentials: 'include'
    }).then((response) => {
      return response.json();
    }).then((result) => {
      const list = result.list;
      const qDList = [];
      const qTList = [];
      list && list.length > 0 && list.forEach((data) => {
        if (data.attenceType == 1 && data.attenceRemark == '签到' || data.attenceType == 2 || data.attenceType == 3) {
          qDList.push(data);
        } else if (data.attenceType == 1 && data.attenceRemark == '签退') {
          qTList.push(data);
        }
      })

      // 已经签到
      if (qDList.length > 0) {
        that.setState({
          signInState: true,
          signInText: `已签到 签到时间：${qDList[0].attenceClockTimeString}`
        });
      } else { // 没签到
        that.setState({
          signInState: false,
          signInText: '签到'
        });
      }

      // 已经签退
      if (qTList.length > 0) {
        that.setState({
          signOutState: true,
          signOutText: `已签退 签退时间：${qTList[qTList.length - 1].attenceClockTimeString}`,
          updateSignOutState: 'block'
        });
      } else { // 没签退
        that.setState({
          signOutState: false,
          signOutText: '签退',
          updateSignOutState: 'none'
        });
      }
    }).catch((err) => {
      console.log('err', err);
    })
  }

  // 签到或签退点击事件
  dakaClick(type) {
    const that = this;
    const name = that.state.name;
    const time = (new Date()).valueOf();
    const token = that.state.token;
    const access_token = that.state.access_token;
    if (name) {
      const data = {
        attencePointAddr: '郑州市中原区', // 位置
        attencePointLongitude: 113.55096821945808, // 经度
        attencePointLatitude: 34.81187630389337, // 纬度
        attenceDeviceID: time, // 打卡时间
        attenceType: 1,
        attenceRemark: type,
        token: token
      }
      fetch('/daka/iSSC/wxapi/v2/save', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer ' + access_token,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data),
        credentials: 'include'
      }).then((response) => {
        return response.json();
      }).then((res) => {
        if (res.ResultCode == 1000) {
          if (type == '签到') {
            that.setState({
              signInState: true,
              signInText: `已签到 签到时间：${res.attenceClockTimeString}`
            });
            Toast.success('签到成功', 1);
          } else if (type == '签退') {
            that.setState({
              signOutState: true,
              signOutText: `已签退 签退时间：${res.attenceClockTimeString}`,
              updateSignOutState: 'block'
            });
            Toast.success('签退成功', 1);
          }
        } else {
          Toast(res.ResultMessage, 1);
        }
      }).catch((err) => {
        console.log('err', err);
      });
    } else {
      Toast.fail('请先获取用户信息');
    }
  }

  render() {
    const that = this;
    return (
      <div className='daka'>
        {/*基本信息*/}
        <List className="daka-info">
          <Item
            className="daka-info-list"
            extra={that.state.name}
          >
            姓名
          </Item>
        </List>
        {/*签到按钮*/}
        <Button
          disabled={that.state.signInState}
          className="sign-in"
          type="primary"
          onClick={() => {
            that.dakaClick('签到');
          }}
        >
          {that.state.signInText}
        </Button>
        {/*签退按钮*/}
        <Button
          disabled={that.state.signOutState}
          className="sign-out"
          type="warning"
          onClick={() => {
            that.dakaClick('签退');
          }}
        >
          {that.state.signOutText}
        </Button>
        {/*更新签退按钮*/}
        <Button
          style={{'display': that.state.updateSignOutState}}
          className="sign-out-update"
          type="warning"
          onClick={() => {
            that.dakaClick('签退');
          }}
        >
          更新签退
        </Button>
      </div>
    );
  };
}